package com.atguigu.day06;

import com.atguigu.day02.Example3;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.triggers.TriggerResult;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new Example3.MySource())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Example3.Event>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner((SerializableTimestampAssigner<Example3.Event>) (element, recordTimestamp) -> element.timestamp)
                )
                .keyBy(x -> true)
                .window(TumblingEventTimeWindows.of(Time.seconds(60)))
                .trigger(new CustomerTrigger())
                .process(new ProcessWindowFunction<Example3.Event, String, Boolean, TimeWindow>() {
                    @Override
                    public void process(Boolean s, Context context, Iterable<Example3.Event> elements, Collector<String> out) throws Exception {
                        System.out.println("窗口 " + context.window().getStart() + "~" + context.window().getEnd() + " 共有" + elements.spliterator().getExactSizeIfKnown() + "个元素");
                    }
                })
                .print();

        env.execute();
    }

    public static class CustomerTrigger extends Trigger<Example3.Event, TimeWindow> {
        @Override
        public TriggerResult onElement(Example3.Event element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {
            ValueState<Boolean> isFirstFlag = ctx.getPartitionedState(new ValueStateDescriptor<Boolean>(
                    "is-isFirstFlag", Boolean.class
            ));
            if (isFirstFlag.value() == null) {
                long windowEnd = window.getEnd();
                for (long i = (timestamp + (10000L - element.timestamp % (10 * 1000L))); i < windowEnd; i = i + 10000L) {
                    ctx.registerEventTimeTimer(i);
                }
                isFirstFlag.update(true);
            }
            return TriggerResult.CONTINUE;
        }

        @Override
        public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
            return TriggerResult.CONTINUE;
        }

        @Override
        public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
            return TriggerResult.FIRE;
        }

        @Override
        public void clear(TimeWindow window, TriggerContext ctx) throws Exception {
            ValueState<Boolean> isFirstEvent = ctx.getPartitionedState(
                    new ValueStateDescriptor<Boolean>("is-isFirstFlag", Types.BOOLEAN)
            );
            isFirstEvent.clear();
        }
    }
}
